<template>
  <el-form :model="editForm" :rules="rules" label-width="135px" ref="editFormRef">
    <div class="bg-white my-[10px]">
      <BaseHead>基本信息</BaseHead>
      <div class="p-[10px]">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="合同编号" prop="code">
              {{ editForm.code ? editForm.code : "审核通过后生成" }}</el-form-item
            >
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同名称" prop="name">
              <el-input v-model="editForm.name" placeholder="合同名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人类型" prop="chargerType">
              <CommonRadio
                :isFetch="false"
                :dataList="memberTypeList"
                v-model="editForm.chargerType"
                valueKey="code"
                @change="chargerTypeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="chargerName">
              <el-autocomplete
                v-model="editForm.chargerName"
                :fetch-suggestions="queryChargerPerosn"
                clearable
                placeholder="请输入检索关键词"
                value-key="name"
                highlight-first-item
                @select="selectChargerPerosn"
                @blur="chargerPerosnBlur"
                v-if="editForm.chargerType != 3"
                :disabled="verifyRoleType.isKyry()"
              >
                <template #default="{ item }">
                  <span>{{ item.name }}</span>
                  <span class="mx-[10px]">{{ item.account }}</span>
                  <span>{{ item.unitName }}</span>
                </template>
              </el-autocomplete>
              <el-input v-else v-model="editForm.chargerName" placeholder="负责人" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人电话" prop="chargerPhone">
              <el-input v-model="editForm.chargerPhone" placeholder="负责人电话" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人邮箱" prop="chargerEmail">
              <el-input v-model="editForm.chargerEmail" placeholder="负责人邮箱" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属单位" prop="unitId">
              <CommonTreeSelect
                placeholder="所属单位"
                v-model="editForm.unitId"
                valueKey="codeColumn"
                labelKey="valueColumn"
                :isFetch="false"
                :dataList="unitList"
                :disabled="editForm.chargerType != 3"
                @change="unitChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人" prop="transactor">
              <el-input v-model="editForm.transactor" placeholder="经办人" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人电话" prop="transactorPhone">
              <el-input v-model="editForm.transactorPhone" placeholder="经办人电话" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同经费" prop="feeAuthorize">
              <el-input
                v-model="editForm.feeAuthorize"
                placeholder="合同经费"
                clearable
                @input="fomateNumber(editForm, 'feeAuthorize', $event)"
                @blur="feeAuthorizeBlur"
              >
                <template #append>万元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同类别" prop="contractType">
              <CommonTreeSelect
                :isFetch="false"
                :dataList="contractTypeList"
                placeholder="合同类别"
                v-model="editForm.contractType"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签订日期" prop="authorizeDate">
              <el-date-picker
                v-model="editForm.authorizeDate"
                type="date"
                clearable
                placeholder="签订日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="beginDate">
              <el-date-picker
                v-model="editForm.beginDate"
                type="date"
                clearable
                placeholder="开始日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="终止日期" prop="planEndDate">
              <el-date-picker
                v-model="editForm.planEndDate"
                type="date"
                clearable
                placeholder="终止日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同有效状态" prop="validState">
              <CommonRadio
                :isFetch="false"
                :dataList="contractEffectiveTypeList"
                v-model="editForm.validState"
                valueKey="code"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进行状态" prop="projectStatusId">
              <CommonRadio
                :isFetch="false"
                :dataList="contractPerformTypeList"
                v-model="editForm.projectStatusId"
                valueKey="code"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付方式" prop="payWay">
              <CommonRadio
                :isFetch="false"
                :dataList="payTypeList"
                v-model="editForm.payWay"
                valueKey="code"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方是否盖章" prop="buyerIsSeal">
              <el-radio-group v-model="editForm.buyerIsSeal">
                <el-radio value="是">是</el-radio>
                <el-radio value="否">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方是否盖章" prop="yfIsSeal">
              <el-radio-group v-model="editForm.yfIsSeal">
                <el-radio value="是">是</el-radio>
                <el-radio value="否">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同是否回收" prop="isRecover">
              <el-radio-group v-model="editForm.isRecover">
                <el-radio value="是">是</el-radio>
                <el-radio value="否">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" prop="signature">
            <el-form-item label="盖章页电子版">
              <FileUpload :uploadUrl="uploadUrl" v-model="fileList" @change="fileChange" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="bg-white">
      <BaseHead>甲方信息</BaseHead>
      <div class="p-[10px]">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="甲方名称" prop="buyerName">
              <el-input v-model="editForm.buyerName" placeholder="甲方名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方类型" prop="buyerType">
              <CommonSelect
                placeholder="甲方类型"
                :isFetch="false"
                :dataList="jfTypeList"
                v-model="editForm.buyerType"
                valueKey="code"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方联系人" prop="buyerChargerName">
              <el-input v-model="editForm.buyerChargerName" placeholder="甲方联系人" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方联系人电话" prop="buyerTel">
              <el-input v-model="editForm.buyerTel" placeholder="甲方联系人电话" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方所属省份" prop="buyerArea">
              <CommonSelect
                placeholder="甲方所属省份"
                :isFetch="false"
                :dataList="provinceList"
                v-model="editForm.buyerArea"
                labelKey="valueColumn"
                valueKey="codeColumn"
                @change="provinceChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方所属地市" prop="buyerCity">
              <CommonSelect
                placeholder="甲方所属地市"
                :isFetch="false"
                :dataList="cityList.value"
                v-model="editForm.buyerCity"
                labelKey="label"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方地址" prop="buyerAddress">
              <el-input v-model="editForm.buyerAddress" placeholder="甲方地址" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方邮编" prop="buyerZipcode">
              <el-input v-model="editForm.buyerZipcode" placeholder="甲方邮编" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="note">
              <el-input
                v-model="editForm.note"
                placeholder="备注"
                type="textarea"
                show-word-limit
                maxlength="500"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="bg-white mt-[10px]">
      <BaseHead>教育部统计信息</BaseHead>
      <div class="p-[10px]">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="统计归属" prop="subjectClassId">
              <CommonRadio
                :isFetch="false"
                :dataList="tjgsList"
                v-model="editForm.subjectClassId"
                valueKey="code"
                @change="tjgschange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="一级学科" prop="subjectId">
              <CommonSelect
                placeholder="一级学科"
                :isFetch="false"
                :dataList="subjectList.value"
                v-model="editForm.subjectId"
                labelKey="label"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="社会经济服务目标" prop="societyTarget">
              <CommonTreeSelect
                :isFetch="false"
                :dataList="jjfwmbList"
                placeholder="社会经济服务目标"
                v-model="editForm.societyTarget"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目来源" prop="projectSourceId">
              <CommonSelect
                placeholder="项目来源"
                :isFetch="false"
                :dataList="projectSourceList.value"
                v-model="editForm.projectSourceId"
                labelKey="label"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="研究类别" prop="researchClassId">
              <CommonSelect
                placeholder="研究类别"
                :isFetch="false"
                :dataList="researchTypeList.value"
                v-model="editForm.researchClassId"
                labelKey="label"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合作形式" prop="cooperateId">
              <CommonSelect
                placeholder="合作形式"
                :isFetch="false"
                :dataList="hzTypeList"
                v-model="editForm.cooperateId"
                valueKey="code"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="国民经济行业" prop="gmjjhy">
              <CommonTreeSelect
                :isFetch="false"
                :dataList="gmjjhyList"
                placeholder="国民经济行业"
                v-model="editForm.gmjjhy"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>
  </el-form>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import CommonRadio from "@/views/project/components/CommonRadio.vue";
import CommonSelect from "@/views/project/components/CommonSelect.vue";
import CommonTreeSelect from "@/views/project/components/CommonTreeSelect.vue";
import FileUpload from "@/views/project/components/FileUpload.vue";
import useCommonFetch from "@/hooks/useCommonFetch";
import { getPersonList } from "@/api/project/common";
import { assignObj } from "@/utils/main";
import { baseDetail } from "@/api/project/zx/lxxm";
import { addRecords, editRecords } from "@/api/project/yf/jzhtqd";
import { verifyRoleType, fomateNumber } from "@/utils/main";
import { emailReg, phoneReg } from "@/utils/validate";
import useUserStore from "@/store/modules/user";
import { ElMessage } from "element-plus";
const userStore = useUserStore();
const memberTypeList = inject("memberTypeList");
const unitList = inject("unitList");
const contractTypeList = inject("contractTypeList");
const contractEffectiveTypeList = inject("contractEffectiveTypeList");
const contractPerformTypeList = inject("contractPerformTypeList");
const payTypeList = inject("payTypeList");
const jfTypeList = inject("jfTypeList");
const provinceList = inject("provinceList");
const tjgsList = inject("tjgsList");
const jjfwmbList = inject("jjfwmbList");
const hzTypeList = inject("hzTypeList");
const gmjjhyList = inject("gmjjhyList");
const isAuditor = inject("isAuditor");
const taskId = inject("taskId");
const checkStatus = inject("checkStatus");
let subjectList = ref([]); //一级学科下拉数据
let researchTypeList = ref([]); //研究类别下拉数据
let projectSourceList = ref([]); //项目来源下拉数据
let cityList = ref([]);
const uploadUrl = `/commonFile/uploadFile?modelName=进账合同签订`;
const fileList = ref([]); //合同附件列表
const editFormRef = ref();
const operateId = ref(null);
const baseInfoData = ref({});
const lastFeeAuthorize = ref(0); //未修改之前的合同经费
const editForm = reactive({
  proClass: "yfContract",
  code: "", //合同编号
  name: "", //项目名称
  chargerType: "", //负责人类型
  chargerName: "", //负责人
  chargerCode: "", //负责人id
  chargerAccount: "", //负责人账号
  chargerPhone: "", //负责人电话
  chargerEmail: "", //负责人邮箱
  unitId: "", //所属单位
  unitName: "", //单位名称
  transactor: "", //经办人
  transactorPhone: "", //经办人电话
  feeAuthorize: "", //合同经费
  contractType: "", //合同类别
  authorizeDate: "", //签订日期
  beginDate: "", //开始日期
  planEndDate: "", //终止日期
  validState: "", //合同有效状态
  projectStatusId: "", //进行状态
  payWay: "", //支付方式
  buyerIsSeal: "否", //甲方是否盖章
  yfIsSeal: "否", //乙方是否盖章
  isRecover: "否", //合同是否回收
  signature: "", //盖章页电子版
  buyerName: "", //甲方名称
  buyerType: "", //甲方类型
  buyerChargerName: "", //甲方联系人
  buyerTel: "", //甲方联系人电话
  buyerArea: "", //甲方所属省份
  buyerCity: "", //甲方所属地市
  buyerAddress: "", //甲方地址
  buyerZipcode: "", //甲方邮编
  note: "",
  subjectClassId: "", //统计归属
  subjectId: "", //一级学科
  societyTarget: "", //社会经济服务目标
  projectSourceId: "", //项目来源
  researchClassId: "", //研究类别
  cooperateId: "", //合作形式
  gmjjhy: "", //国民经济行业
});
//验证签订日期
const validateAuthorizeDate = (rule, value, callback) => {
  if (editForm.planEndDate) {
    if (new Date(value).getTime() >= new Date(editForm.planEndDate).getTime()) {
      callback(new Error("签订日期必须早于终止日期"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
//验证终止日期
const validatePlanEndDate = (rule, value, callback) => {
  if (value) {
    if (editForm.authorizeDate || editForm.beginDate) {
      if (editForm.authorizeDate && editForm.beginDate) {
        if (
          new Date(value).getTime() <= new Date(editForm.authorizeDate).getTime() &&
          new Date(value).getTime() <= new Date(editForm.beginDate).getTime()
        ) {
          callback(new Error("终止日期必须晚于签订日期、开始日期"));
        } else if (new Date(value).getTime() <= new Date(editForm.authorizeDate).getTime()) {
          callback(new Error("终止日期必须晚于签订日期"));
        } else if (new Date(value).getTime() <= new Date(editForm.beginDate).getTime()) {
          callback(new Error("终止日期必须晚于开始日期"));
        } else {
          callback();
        }
      } else if (editForm.authorizeDate) {
        if (new Date(value).getTime() <= new Date(editForm.authorizeDate).getTime()) {
          callback(new Error("终止日期必须晚于签订日期"));
        } else {
          callback();
        }
      } else if (editForm.beginDate) {
        if (new Date(value).getTime() <= new Date(editForm.beginDate).getTime()) {
          callback(new Error("终止日期必须晚于开始日期"));
        } else {
          callback();
        }
      }
    } else {
      callback();
    }
  } else {
    callback();
  }
};
//验证开始日期
const validateBeginDate = (rule, value, callback) => {
  if (value) {
    if (editForm.planEndDate) {
      if (new Date(value).getTime() >= new Date(editForm.planEndDate).getTime()) {
        callback(new Error("开始日期必须早于终止日期"));
      } else {
        callback();
      }
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const rules = {
  name: [
    {
      required: true,
      message: "项目名称必填",
    },
  ],
  chargerName: [
    {
      required: true,
      message: "负责人必填",
    },
  ],
  chargerPhone: [
    {
      required: true,
      message: "负责人电话必填",
    },
    {
      pattern: phoneReg,
      message: "请输入正确的电话号码",
    },
  ],
  chargerEmail: [
    {
      pattern: emailReg,
      message: "请输入正确的邮箱地址",
    },
  ],
  unitId: [
    {
      required: true,
      message: "所属单位必填",
    },
  ],
  transactorPhone: [
    {
      pattern: phoneReg,
      message: "请输入正确的电话号码",
    },
  ],
  feeAuthorize: [
    {
      required: true,
      message: "合同经费必填",
    },
  ],
  contractType: [
    {
      required: true,
      message: "合同类别必填",
    },
  ],
  authorizeDate: [
    {
      required: true,
      message: "签订日期必填",
    },
    { validator: validateAuthorizeDate, trigger: "blur" },
  ],
  beginDate: [{ validator: validateBeginDate, trigger: "blur" }],
  planEndDate: [{ validator: validatePlanEndDate, trigger: "blur" }],
  validState: [
    {
      required: true,
      message: "合同有效状态必填",
    },
  ],
  payWay: [
    {
      required: true,
      message: "支付方式必填",
    },
  ],
  buyerName: [
    {
      required: true,
      message: "甲方名称必填",
    },
  ],
  buyerChargerName: [
    {
      required: true,
      message: "甲方联系人必填",
    },
  ],
  buyerTel: [
    {
      required: true,
      message: "甲方联系人电话必填",
    },
    {
      pattern: phoneReg,
      message: "请输入正确的电话号码",
    },
  ],
  buyerArea: [
    {
      required: true,
      message: "甲方所属省份必填",
    },
  ],
  subjectClassId: [
    {
      required: true,
      message: "统计归属必填",
    },
  ],
  subjectId: [
    {
      required: true,
      message: "一级学科必填",
    },
  ],
  societyTarget: [
    {
      required: true,
      message: "社会经济服务目标必填",
    },
  ],
  projectSourceId: [
    {
      required: true,
      message: "项目来源必填",
    },
  ],
  researchClassId: [
    {
      required: true,
      message: "研究类别必填",
    },
  ],
  cooperateId: [
    {
      required: true,
      message: "合作形式必填",
    },
  ],
  gmjjhy: [
    {
      required: true,
      message: "国民经济行业必填",
    },
  ],
};
const emit = defineEmits(["save-success", "save-ok"]);
//获取详情
const getBaseInfoData = async () => {
  try {
    const res = await baseDetail(operateId.value);
    baseInfoData.value = res.data;
    fileList.value = res.data.signatureList || [];
    lastFeeAuthorize.value = res.data.feeAuthorize;
  } catch (error) {
    console.log(error);
  }
};
// 新增
const add = () => {
  operateId.value = null;
  //科研管理员新增默认负责人是自己
  if (verifyRoleType.isKyry()) {
    editForm.chargerName = userStore.nickName;
    editForm.chargerCode = userStore.userRealId;
    editForm.chargerAccount = userStore.account;
    editForm.chargerPhone = userStore.phonenumber;
    editForm.chargerEmail = userStore.email;
    editForm.unitId = userStore.deptId;
    editForm.unitName = userStore.deptName;
  }
};
// 编辑
const edit = async (id) => {
  operateId.value = id;
  nextTick(async () => {
    await getBaseInfoData();
    //表单表格赋值
    assignObj(editForm, baseInfoData.value);
    cityList.value = useCommonFetch("甲方所属地市", editForm.buyerArea);
  });
};
const save = async (submitType) => {
  try {
    await editFormRef.value?.validate(async (valid) => {
      if (valid) {
        let res;
        let params = {
          ...editForm,
          submitType,
          isAuditor: isAuditor.value,
          taskId: taskId.value,
          checkstatus: checkStatus.value,
        };
        if (operateId.value) {
          params.id = operateId.value;
          res = await editRecords(params);
        } else {
          res = await addRecords(params);
        }
        if (res.code === 200) {
          emit("save-success", res.data);
        }
      }
    });
  } catch (error) {
    console.log(error);
  } finally {
    emit("save-ok");
  }
};
defineExpose({ add, edit, save });
//项目总经费输入框失去焦点
const feeAuthorizeBlur = () => {
  if (operateId.value && lastFeeAuthorize.value != editForm.feeAuthorize) {
    ElMessage({
      message: `合同经费已经更改，请修改预算明细！`,
      type: "warning",
    });
  }
};
//选择的省份改变
const provinceChange = () => {
  editForm.buyerCity = "";
  cityList.value = useCommonFetch("甲方所属地市", editForm.buyerArea);
};
//根据姓名查询负责人
const queryChargerPerosn = async (queryString, cb) => {
  if (queryString.trim() == "") {
    return;
  }
  //输入时清空chargerCode结合blur事件，控制负责人必须是选择的下拉框的值
  editForm.chargerCode = "";
  const params = {
    name: queryString,
  };
  try {
    const res = await getPersonList(params);
    cb(res.data);
  } catch (error) {
    console.log(error);
  }
};

//选择负责人
const selectChargerPerosn = (val) => {
  editForm.chargerCode = val.id;
  editForm.chargerEmail = val.email;
  editForm.chargerPhone = val.mobile;
  editForm.chargerAccount = val.account;
  editForm.unitId = val.unitId;
  editForm.unitName = val.unitName;
};
//清空负责人字段的值
const resetChargerPerosn = () => {
  editForm.chargerCode = "";
  editForm.chargerName = "";
  editForm.chargerEmail = "";
  editForm.chargerPhone = "";
  editForm.chargerAccount = "";
  editForm.unitId = "";
  editForm.unitName = "";
};
//选择负责人框失去焦点
const chargerPerosnBlur = () => {
  if (!editForm.chargerCode) {
    resetChargerPerosn();
  }
};
//负责人类型改变
const chargerTypeChange = (val) => {
  if (verifyRoleType.isKyry()) {
    //校内和学生类型默认取当前登录人为负责人
    if (val == 1 || val == 2) {
      editForm.chargerName = userStore.nickName;
      editForm.chargerCode = userStore.userRealId;
      editForm.chargerPhone = userStore.phonenumber;
      editForm.chargerEmail = userStore.email;
      editForm.chargerAccount = userStore.account;
      editForm.unitId = userStore.deptId;
      editForm.unitName = userStore.deptName;
    } else {
      resetChargerPerosn();
    }
  } else {
    //选择校外时或者从校外选择校内或学生时 清空负责人的值
    if (val == 3 || (val != 3 && editForm.chargerCode == "")) {
      resetChargerPerosn();
    }
  }
};
//选择的单位改变 设置unitName的值
const unitChange = (val) => {
  unitList.value.forEach((item) => {
    if (item.codeColumn == val) {
      editForm.unitName = item.valueColumn;
    }
  });
};
//上传盖章附件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  editForm.signature = ids.join(",");
};
//监听统计归属的值改变
watch(
  () => editForm.subjectClassId,
  (newVal) => {
    subjectList.value = useCommonFetch("一级学科", newVal);
    researchTypeList.value = useCommonFetch("研究类别", newVal);
    projectSourceList.value = useCommonFetch("项目来源", newVal);
  }
);
//手动改变统计归属的值 清空一级学科、项目来源、研究类别的值
const tjgschange = () => {
  editForm.subjectId = "";
  editForm.projectSourceId = "";
  editForm.researchClassId = "";
};
</script>

<style scoped lang="scss"></style>
